let socketInstance;

const PlatformSocket = {
    vm: undefined,

    wsURL: undefined,

    /**
     * 创建连接
     * @param userId
     * @param vm
     */
    createConnect (userId, vm){
        let wsBaseUrl = process.env.NODE_ENV === 'production' ? window.location.host + '/__api' : '127.0.0.1:8080';

        this.wsURL = `ws://${wsBaseUrl}/api/ws/lt/telemetry`;

        this.vm = vm;

        if(userId){
            //建立webSocket连接
            socketInstance = new WebSocket(PlatformSocket.wsURL);

            bindSocketEvent(this.vm, userId);
        }
    },

    /**
     * 重置连接
     */
    resetConnect (){
        setSocketToken(this.vm);
    },

    /**
     * 关闭连接
     */
    closeConnect (){
        socketInstance && socketInstance.close();
    }
};

function setSocketToken(vm) {
    let token = vm.$token.getToken().replace("Bearer ",'');

    vm.$busBroadcast('socket.message.send', { type: 'set-token', content: { token } });
}

function bindSocketEvent(vm, userId) {
    //打开webSocket连接时，回调该函数
    socketInstance.onopen = function () {
        vm.$busListener && vm.$busListener.call({
            _uid: Date.now()
        }, 'socket.message.send', sendMessage);

        setSocketToken(vm);

        vm.$busBroadcast('socket-connection');

        function sendMessage(message) {
            try {
                socketInstance && socketInstance.send(JSON.stringify(message));
            }catch (e) {
                console.log('' +
                    '，序列化失败，发送内容：', message);
            }
        }

        setInterval(function () {
            sendMessage({ type: 'heartbeat' });
        }, 15 * 1000);
    };

    //关闭socket连接时，回调该函数
    socketInstance.onclose = function (e) {
        vm.$notify({
            title: '警告',
            message: "实时数据断开链接，5秒后重试..",
            type: 'warning',
            offset: 60
        });

        socketInstance && socketInstance.close();

        setTimeout(()=>{
            socketInstance = new WebSocket(PlatformSocket.wsURL);

            bindSocketEvent(vm);
        },5000);

        //关闭连接
        console.log("onclose");
    };

    //接收信息
    socketInstance.onmessage = function (messageEvent) {
        // console.log('receive socket message: ', messageEvent);
        try {
            let { type, payload } = JSON.parse(messageEvent.data);

            //判断返回的accountId和当前userId是否相同，如果不相同就不提示
            switch (type) {
                case 'warn-notification':
                    //接收到告警通知后，请求最新的告警数据
                    vm.$busBroadcast('socket.message.send', { type: 'get-realtime-warn' });

                    playNotification(payload.deviceName, payload.remark, payload.lvl);

                    vm.$busBroadcast('warn-notification', payload);
                    break;
                case 'realtime-data':
                    vm.$busBroadcast('realtime-data', payload);
                    break;
                case 'realtime-warn':
                    vm.$busBroadcast('realtime-warn', payload);
                    break;
                case 'monitor-data':
                    vm.$busBroadcast('monitor-data', payload);
                    break;
                case 'monitor-chart':
                    vm.$busBroadcast('monitor-data', payload);
                    break;
                case 'device-offline':
                    vm.$busBroadcast('device-offline-update', payload);

                    if(payload.notifyUserUUID && payload.notifyUserUUID === userId){
                        vm.$busBroadcast('device-offline-notify', payload);

                        playNotification(payload.deviceName, payload.remark, payload.lvl);

                        //接收到告警通知后，请求最新的告警数据
                        vm.$busBroadcast('socket.message.send', { type: 'get-realtime-warn' });
                    }
                    break;
                case 'device-data-one':
                    vm.$busBroadcast('device-data-one', payload);
                    break;
                case 'token-expired':
                    vm.$busBroadcast('token-expired');
            }
        } catch (e) {
            console.log('反序列化socket消息失败，返回内容：', messageEvent);
        }

        function playNotification(deviceName, message, level) {
            let notifyText = !!deviceName ? `【${deviceName}】${message}` : message;

            message && vm.$pushText2VoiceNotification({
                text: message,
                callback (){
                    vm.$notify({
                        title: {
                            low: '低级',
                            mid: '中级',
                            high: '高级',
                        }[level] + '告警',
                        message: notifyText,
                        type: {
                            low: 'info',
                            mid: 'warning',
                            high: 'error',
                        }[level],
                        offset: 60
                    });
                }
            });
        }
    }
}

export default PlatformSocket;
